package com.leo.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.filter.DelegatingFilterProxy;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.util.EnumSet;

/**
 * @ClassName: Config
 * @Description: ${description}
 * @Author: leo825
 * @Date: 2020-02-04 09:10
 * @Version: 1.0
 */

public class MyFilterConfig implements WebApplicationInitializer {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyFilterConfig.class);

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        DelegatingFilterProxy delegatingFilterProxy = new DelegatingFilterProxy();
        //Bean实例名称
        String BeanId = "myFilter5";
        //代理的过滤器的Bean
        delegatingFilterProxy.setTargetBeanName(BeanId);
        //设置"targetFilterLifecycle"为True，则spring来管理Filter.init()和Filter.destroy()；若为false，则这两个方法失效！
        delegatingFilterProxy.setTargetFilterLifecycle(true);
        //注册过滤器
        FilterRegistration filterRegistration = servletContext.addFilter(BeanId, delegatingFilterProxy);
        filterRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
        LOGGER.info("代理拦截器，将Bean注入到Web容器中");
    }
}
